//
//  JourneyDetailsViewController.m
//  MyTravel
//
//  Created by Hunk on 11-5-25.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "JourneyDetailsViewController.h"
#import "AsyncLoadingImageView.h"
#import "StowView.h"
#import "ShowImageViewController.h"
#import "NetworkManager.h"
#import <QuartzCore/QuartzCore.h>
#import "MyLoadingView.h"
#import "BottomView.h"
#import "ShowSightsViewController.h"
#import "NSString+URLEncoding.h"
#import "SendMessageViewController.h"

#define TAG_ASYNCIMAGE (100)
#define TAG_TOOLBAR (11)
#define TAG_STOWITEM (12)
#define TAG_ACTIONITEM (13)
#define TAG_COMPOSEITEM (14)
#define TAG_TABLEVIEW (34)

#define STOW   @"☆"
#define UNSTOW @"★"

#define TAG_LOADINGLABEL (27)
#define TAG_ACTIVITYINDICATORVIEW (28)

#define SHOWACTIVITYINDICATOR UIActivityIndicatorView* activityIndicatorView = (UIActivityIndicatorView*)[self.view viewWithTag:TAG_ACTIVITYINDICATORVIEW]; if([activityIndicatorView isAnimating]) {[activityIndicatorView stopAnimating];}else{[activityIndicatorView startAnimating];}

@interface JourneyDetailsViewController (Private)

-(void)addLabelOnCell:(UITableViewCell*)cell
                 text:(NSString*)text
                frame:(CGRect)frame
              bgColor:(UIColor*)bgColor 
            textColor:(UIColor*)textColor 
           fontOfSize:(UIFont*)fontOfSize 
        lineBreakMode:(UILineBreakMode)lineBreakMode 
        textAlignment:(UITextAlignment)textAlignment;

- (void)loadData;

@end

@implementation JourneyDetailsViewController
@synthesize journeyId, isMyFavorite, journeyName;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    SAFE_RELEASE(arrayJourneyDetails)
    SAFE_RELEASE(_engine)
    
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];

    [self setTitle:@"行程参考"];
    
    // Init array
    arrayJourneyDetails = [[NSMutableArray alloc] init];
    bIsLoading = NO;
        
    // Add tableView
    UITableView* tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 416)
                                                          style:UITableViewStylePlain];
    //tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [tableView setDelegate:self];
    [tableView setDataSource:self];
    [tableView setTag:TAG_TABLEVIEW];
    [self.view addSubview:tableView];
    [tableView release];
    
    UIBarButtonItem* shareButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"weiboLogo.png"] style:UIBarButtonItemStylePlain target:self action:@selector(shareButtonHandle:)] autorelease];
    
    self.navigationItem.rightBarButtonItem = shareButtonItem;
    
    // Toolbar
    /*
    UIToolbar* toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, (416 - 44), 320, 44)];
    toolbar.barStyle = UIBarStyleBlack;
    toolbar.tintColor = TINTCOLOR;
    [toolbar setTag:TAG_TOOLBAR];
    UIBarButtonItem* flexibleSpaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    
    [UIApplication sharedApplication].idleTimerDisabled = YES;
    
    // 收藏
    UIBarButtonItem* stowItem;
    if([isMyFavorite isEqualToString:@"1"])
    {
        stowItem = [[UIBarButtonItem alloc] initWithTitle:UNSTOW style:UIBarButtonItemStylePlain target:self action:@selector(toolbarButtonItemHandle:)];
    }
    else
    {
        stowItem = [[UIBarButtonItem alloc] initWithTitle:STOW style:UIBarButtonItemStylePlain target:self action:@selector(toolbarButtonItemHandle:)];
    }
    [stowItem setTag:TAG_STOWITEM];
    
    UIBarButtonItem* actionItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(toolbarButtonItemHandle:)];
    [actionItem setTag:TAG_ACTIONITEM];
    UIBarButtonItem* composeItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCompose target:self action:@selector(toolbarButtonItemHandle:)];
    [composeItem setTag:TAG_COMPOSEITEM];
    [toolbar setItems:[NSArray arrayWithObjects:
                       flexibleSpaceItem,
                       stowItem,
                       flexibleSpaceItem,
                       actionItem,
                       flexibleSpaceItem,
                       composeItem, 
                       flexibleSpaceItem, nil]
             animated:YES];
    [flexibleSpaceItem release];
    [stowItem release];
    [actionItem release];
    [composeItem release];
    
    [self.view addSubview:toolbar];
    [toolbar release];
    */
    
    // Data
    m_nDayNumber = 1;
    
    NSDictionary* parameters = [NSDictionary dictionaryWithObjectsAndKeys:
                                journeyId, @"journeyId", 
                                [NSString stringWithFormat:@"%d", m_nDayNumber], @"day", nil];
    
    [[NetworkManager sharedNetworkManager] requestServerForMethod:NetworkRequest_GetJourneyDetails
                                                   WithParameters:parameters
                                                 AndCallBackScope:self
                                                    AndSuccessSel:@"onSuccess:"
                                                     AndFailedSel:@"onFailed:"];
    [[MyLoadingView sharedMyLoadingView] startLoadingAnimation];
}

#pragma mark -
#pragma mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
    return [arrayJourneyDetails count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{
    return 6;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary* detailsDic = [arrayJourneyDetails objectAtIndex:indexPath.section];
    
    if(detailsDic && 0 != [[detailsDic allKeys] count])
    {
        switch (indexPath.row)
        {
            case 0: // introduction_image
                return 202.0f;
                break;
//            case 1: // introduction_info
//            {   
//                return 50.0f;
//                /*
//                NSString* infoString = [detailsDic objectForKey:@"introduction_info"];
//                CGSize size = [infoString sizeWithFont:[UIFont systemFontOfSize:16.0] 
//                                     constrainedToSize:CGSizeMake(290, 1000) lineBreakMode:UILineBreakModeCharacterWrap];
//                
//                return (size.height > 50.0) ? (size.height + 10.0f) : 50.0;
//                */
//            }
//                break;
            case 2: // sight_names
            {
                NSString* sightNamesString = [detailsDic objectForKey:@"sight_names"];
                if([sightNamesString length])
                {
                    NSArray* arraySights = [sightNamesString componentsSeparatedByString:@"[OVER]"];
                    
                    return ([arraySights count] > 1) ? (10.0f + [arraySights count] * 30.0f) : 50.0f;
                }
                else
                {
                    return 50.0f;
                }
            }
                break;
            case 1: // introduction_info
            case 3: // breakfast & lunch & supper
            case 4: // stay
            case 5: // tranffic
            {
                return 50.0f;
            }
                break;
            default:
                break;
        }
    }
    
    return 50.0f;
}

//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//{
//    // Background view 
//    UIImageView* imageView = [[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 30)] autorelease];
//    [imageView setImage:[UIImage imageNamed:@"sectionHeaderView.png"]];
//    
//    // Info button
//    UIButton* infoButton = [UIButton buttonWithType:UIButtonTypeInfoDark];
//    [infoButton setFrame:CGRectMake(300, 5, 20, 20)];
//    [imageView addSubview:infoButton];
//    
//    
//    return imageView;
//}

- (NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSDictionary* detailsDic = [arrayJourneyDetails objectAtIndex:section];
    
    if(detailsDic && 0 != [[detailsDic allKeys] count])
    {
        return [NSString stringWithFormat:@"第%d天:%@", (section + 1), [detailsDic objectForKey:@"introduction_title"]];
    }
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{    
    static NSString *CellIdentifier = @"Cell";
	UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
                                   reuseIdentifier:CellIdentifier] autorelease];
    
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    NSDictionary* detailsDic = [arrayJourneyDetails objectAtIndex:indexPath.section];
    
    if(detailsDic && 0 != [[detailsDic allKeys] count])
    {
        switch (indexPath.row)
        {
            case 0: // introduction_image
            {
                // Cell background view
                UIView* cellBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320.0f, 200.0f)];
                UIImageView* bgImageView = [[UIImageView alloc] initWithFrame:cellBgView.frame];
                UIImage* image = [UIImage imageNamed:@"CellBackground.png"];
                image = [image stretchableImageWithLeftCapWidth:5 topCapHeight:5];
                [bgImageView setImage:image];
                [cellBgView addSubview:bgImageView];
                [bgImageView release];
                [cell setBackgroundView:cellBgView];
                [cellBgView release];
                
                // Image
                AsyncLoadingImageView* asyncLoadingImageView = [[AsyncLoadingImageView alloc] initWithFrame:CGRectMake(1, 1, 318, 200)];
                
                NSString* imageString = PATH_JOURNEYBASEINFO_IMAGE([journeyName URLEncodedString],[detailsDic objectForKey:@"introduction_image"]);
                
                [asyncLoadingImageView loadImageFromURLString:imageString
                                             placeholderImage:nil];
                asyncLoadingImageView.layer.cornerRadius = 8.0;
                asyncLoadingImageView.layer.masksToBounds = YES;
                asyncLoadingImageView.tag = TAG_ASYNCIMAGE + indexPath.section;// Is indexPath.section, NOT row
                [cell.contentView addSubview:asyncLoadingImageView];
                [asyncLoadingImageView release];
            }
                break;
            case 1: // introduction_info
            {
                cell.selectionStyle = UITableViewCellSelectionStyleBlue;
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            //    NSString* infoString = [detailsDic objectForKey:@"introduction_info"];
                
//                CGSize size = [infoString sizeWithFont:[UIFont systemFontOfSize:16.0] 
//                                     constrainedToSize:CGSizeMake(290, 1000) lineBreakMode:UILineBreakModeCharacterWrap];
                //float fHeight = (size.height > 50.0) ? (size.height + 10.0f) : 50.0;

                // Cell background view
                UIView* cellBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
                UIImageView* bgImageView = [[UIImageView alloc] initWithFrame:cellBgView.frame];
                UIImage* image = [UIImage imageNamed:@"CellBackground.png"];
                image = [image stretchableImageWithLeftCapWidth:5 topCapHeight:5];
                [bgImageView setImage:image];
                [cellBgView addSubview:bgImageView];
                [bgImageView release];
                [cell setBackgroundView:cellBgView];
                [cellBgView release];
                
                // Schedule
                UILabel* scheduleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 80, 40)];
                scheduleLabel.backgroundColor = [UIColor clearColor];
                scheduleLabel.textColor = [UIColor blackColor];
                scheduleLabel.font = [UIFont boldSystemFontOfSize:18];
                scheduleLabel.text = @"日程安排:";
                [cell.contentView addSubview:scheduleLabel];
                [scheduleLabel release];
                
                [self addLabelOnCell:cell
                                text:[detailsDic objectForKey:@"introduction_details"]
                               frame:CGRectMake(100, 5, 200, 40)
                             bgColor:[UIColor clearColor]
                           textColor:TEXTCOLOR
                          fontOfSize:[UIFont systemFontOfSize:18]
                       lineBreakMode:UILineBreakModeTailTruncation
                       textAlignment:UITextAlignmentCenter];
                
//                // Info label
//                UILabel* infoLabel = [[UILabel alloc] init];
//                infoLabel.backgroundColor = [UIColor clearColor];
//                infoLabel.textColor = [UIColor blackColor];
//                infoLabel.font = [UIFont systemFontOfSize:16.0];
//                infoLabel.textAlignment = UITextAlignmentLeft;
//                infoLabel.lineBreakMode = UILineBreakModeWordWrap;
//                infoLabel.text = @"行程介绍行程介绍行程介绍行程介绍行程介绍";
//                //[detailsDic objectForKey:@"introduction_info"];
//                [infoLabel setFrame:CGRectMake(10, 4, 300, 50)];
//                [cell.contentView addSubview:infoLabel];
//                [infoLabel release];
                
                /*
                NSString* detailsString = [detailsDic objectForKey:@"introduction_details"];
                if(0 != [detailsString length])
                {
                    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                }
                else
                {
                    cell.accessoryType = UITableViewCellAccessoryNone;
                }
                */
            }
                break;
            case 2: // sight
            {  
            //    cell.selectionStyle = UITableViewCellSelectionStyleBlue;
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
      //          NSString* sight_namesString = [detailsDic objectForKey:@"sight_names"];
                
                NSString* sightNamesString = [detailsDic objectForKey:@"sight_names"];
                
                if(0 != [sightNamesString length])
                {
                    NSArray* arraySights = [sightNamesString componentsSeparatedByString:@"[OVER]"];
                    
                    float fCellHeight = ([arraySights count] > 1 ? (10.0f + [arraySights count] * 30.0f) : 50.0f); 
                    
                    // Cell background view
                    UIView* cellBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, fCellHeight)];
                    UIImageView* bgImageView = [[UIImageView alloc] initWithFrame:cellBgView.frame];
                    UIImage* image = [UIImage imageNamed:@"CellBackground.png"];
                    image = [image stretchableImageWithLeftCapWidth:5 topCapHeight:5];
                    [bgImageView setImage:image];
                    [cellBgView addSubview:bgImageView];
                    [bgImageView release];
                    [cell setBackgroundView:cellBgView];
                    [cellBgView release];
                    
                    // Sight
                    UILabel* sightLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 80, 40)];
                    sightLabel.backgroundColor = [UIColor clearColor];
                    sightLabel.textColor = [UIColor blackColor];
                    sightLabel.font = [UIFont boldSystemFontOfSize:18];
                    sightLabel.text = @"途经景点:";
                    [cell.contentView addSubview:sightLabel];
                    [sightLabel release];
                    
                    if(1 == [arraySights count])
                    {
                        NSString* sightName = [arraySights objectAtIndex:0];
                        
                        UILabel* sightNameLabel = [[UILabel alloc] init];
                        sightNameLabel.frame = CGRectMake(10, 0, 180, 30);
                        sightNameLabel.backgroundColor = [UIColor clearColor];
                        [sightNameLabel setTextColor:TEXTCOLOR];
                        sightNameLabel.font = [UIFont fontWithName:@"AmericanTypewriter" size:18];
                        sightNameLabel.text = [NSString stringWithFormat:@"%@", sightName];
                    
                        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
                        [button setFrame:CGRectMake(100, 10, 190, 30)];
                        [button addTarget:self 
                                   action:@selector(sightButtonHandle:) 
                         forControlEvents:UIControlEventTouchUpInside];
                        [button addSubview:sightNameLabel];
                        [sightNameLabel release];
                        [cell.contentView addSubview:button];
                    }
                    else
                    {
                        for(int i = 0; i < [arraySights count]; i++)
                        {   
                            NSString* sightName = [arraySights objectAtIndex:i];
                            
                            UILabel* sightNameLabel = [[UILabel alloc] init];
                            sightNameLabel.frame = CGRectMake(10, 0, 180, 30);
                            sightNameLabel.backgroundColor = [UIColor clearColor];
                            [sightNameLabel setTextColor:TEXTCOLOR];
                            sightNameLabel.font = [UIFont fontWithName:@"AmericanTypewriter" size:18];
                            sightNameLabel.text = [NSString stringWithFormat:@"%d.%@", (i + 1), sightName];
                            
                            UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
                            [button setFrame:CGRectMake(100, 2 + i * 31, 190, 30)];
                            [button addTarget:self 
                                       action:@selector(sightButtonHandle:) 
                             forControlEvents:UIControlEventTouchUpInside];
                            [button addSubview:sightNameLabel];
                            [sightNameLabel release];
                            [cell.contentView addSubview:button];
                        }
                    }
                }
                else
                {
                    cell.accessoryType = UITableViewCellAccessoryNone;
                    
                    // Cell background view
                    UIView* cellBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 50.0f)];
                    
                    UIImageView* bgImageView = [[UIImageView alloc] initWithFrame:cellBgView.frame];
                    UIImage* image = [UIImage imageNamed:@"CellBackground.png"];
                    image = [image stretchableImageWithLeftCapWidth:5 topCapHeight:5];
                    [bgImageView setImage:image];
                    [cellBgView addSubview:bgImageView];
                    [bgImageView release];
                    [cell setBackgroundView:cellBgView];
                    [cellBgView release];
                    
                    // Sight
                    UILabel* sightLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 80, 40)];
                    sightLabel.backgroundColor = [UIColor clearColor];
                    sightLabel.textColor = [UIColor blackColor];
                    sightLabel.font = [UIFont boldSystemFontOfSize:18];
                    sightLabel.text = @"途经景点:";
                    [cell.contentView addSubview:sightLabel];
                    [sightLabel release];
                    
                    UILabel* sightNameLabel = [[UILabel alloc] init];
                    sightNameLabel.frame = CGRectMake(100, 5, 200, 40);
                    sightNameLabel.backgroundColor = [UIColor clearColor];
                    [sightNameLabel setTextColor:TEXTCOLOR];
                    sightNameLabel.font = [UIFont systemFontOfSize:18];
                    sightNameLabel.text = @"无";//@"暂时未定";
                    [cell.contentView addSubview:sightNameLabel];
                    [sightNameLabel release];
                }
                /////////////
                /*
                if([sight_namesString length])
                {
                    NSArray* arraySight = [sight_namesString componentsSeparatedByString:@"[OVER]"];
                    
                    float fHeightOfRow = 50.0f;
                    
                    if([arraySight count] != 1)
                    {
                        fHeightOfRow = (10.0f + [arraySight count] * 30.0f);
                    }
                    else
                    {
                        fHeightOfRow = 50.0f;
                    }

                    // Cell background view
                    UIView* cellBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, fHeightOfRow)];
                    UIImageView* bgImageView = [[UIImageView alloc] initWithFrame:cellBgView.frame];
                    UIImage* image = [UIImage imageNamed:@"CellBackground.png"];
                    image = [image stretchableImageWithLeftCapWidth:5 topCapHeight:5];
                    [bgImageView setImage:image];
                    [cellBgView addSubview:bgImageView];
                    [bgImageView release];
                    [cell setBackgroundView:cellBgView];
                    [cellBgView release];
                    
                    // Sight
                    UILabel* sightLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 80, 40)];
                    sightLabel.backgroundColor = [UIColor clearColor];
                    sightLabel.textColor = [UIColor blackColor];
                    sightLabel.font = [UIFont systemFontOfSize:18];
                    sightLabel.text = @"途经景点:";
                    [cell.contentView addSubview:sightLabel];
                    [sightLabel release];
                    
                    if(0 == [arraySight count])
                    {
                        UILabel* sightNameLabel = [[UILabel alloc] init];
                        sightNameLabel.frame = CGRectMake(100, 5, 210, 30);
                        sightNameLabel.backgroundColor = [UIColor clearColor];
                        sightNameLabel.font = [UIFont systemFontOfSize:18];
                        sightNameLabel.text = @"暂时未定";
                        [cell.contentView addSubview:sightNameLabel];
                        [sightNameLabel release];
                    }
                    else
                    {   
                        for(int i = 0; i < [arraySight count]; i++)
                        {   
                            NSString* sightName = [arraySight objectAtIndex:i];
                            
                            UIView* sightView =[[UIView alloc] initWithFrame:CGRectMake(100, 5+i*30,210, 40)];
                            [sightView setBackgroundColor:[UIColor clearColor]];
                            
                            UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
                            [button setFrame:CGRectMake(0, 0, 210, 29)];
                            [button addTarget:self 
                                       action:@selector(sightButtonHandle:) 
                             forControlEvents:UIControlEventTouchUpInside];
                            [button setTag:i + 45];
                            
                            UILabel* sightNameLabel = [[UILabel alloc] init];
                            sightNameLabel.frame = CGRectMake(10, 0, 200, 29);
                            sightNameLabel.backgroundColor = [UIColor clearColor];
                            sightNameLabel.font = [UIFont fontWithName:@"AmericanTypewriter" size:18];
                            sightNameLabel.text = [NSString stringWithFormat:@"%d.%@", (i + 1), sightName];
                            [button addSubview:sightNameLabel];
                            [sightNameLabel release];
                            
                            [sightView addSubview:button];
                            
                            [cell.contentView addSubview:sightView];
                            [sightView release];
                        }
                    }
                }
                else
                {
                    // Row's height
                    float fHeightOfRow = 50.0f;
                    
                    // Cell background view
                    UIView* cellBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, fHeightOfRow)];
                    UIImageView* bgImageView = [[UIImageView alloc] initWithFrame:cellBgView.frame];
                    UIImage* image = [UIImage imageNamed:@"CellBackground.png"];
                    image = [image stretchableImageWithLeftCapWidth:5 topCapHeight:5];
                    [bgImageView setImage:image];
                    [cellBgView addSubview:bgImageView];
                    [bgImageView release];
                    [cell setBackgroundView:cellBgView];
                    [cellBgView release];
                    
                    // Sight
                    UILabel* sightLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 80, 40)];
                    sightLabel.backgroundColor = [UIColor clearColor];
                    sightLabel.textColor = [UIColor blackColor];
                    sightLabel.font = [UIFont systemFontOfSize:18];
                    sightLabel.text = @"途经景点:";
                    [cell.contentView addSubview:sightLabel];
                    [sightLabel release];
                    
                    UILabel* sightNameLabel = [[UILabel alloc] init];
                    sightNameLabel.frame = CGRectMake(100, 5, 210, 40);
                    sightNameLabel.backgroundColor = [UIColor clearColor];
                    sightNameLabel.font = [UIFont systemFontOfSize:18];
                    sightNameLabel.text = @"暂时未定";
                    [cell.contentView addSubview:sightNameLabel];
                    [sightNameLabel release];
                }
                */
            }
                break;
            case 3: // breakfast & lanch & supper
            {
             //   cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
             //   cell.selectionStyle = UITableViewCellSelectionStyleBlue;
                
                // Cell background view
                UIView* cellBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
                UIImageView* bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
                [bgImageView setImage:[UIImage imageNamed:@"CellBackground.png"]];
                [cellBgView addSubview:bgImageView];
                [bgImageView release];
                [cell setBackgroundView:cellBgView];
                [cellBgView release];
                
                // Breakfast
                UILabel* breakfastLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 50, 30)];
                breakfastLabel.backgroundColor = [UIColor clearColor];
                breakfastLabel.font = [UIFont boldSystemFontOfSize:18];
                breakfastLabel.textColor = [UIColor blackColor];
                breakfastLabel.text = @"早餐:";
                [cell.contentView addSubview:breakfastLabel];
                [breakfastLabel release];
                
                // Breakfast array
                NSArray* arrayBreakfast = [[detailsDic objectForKey:@"breakfast"] componentsSeparatedByString:@"[OVER]"];
                
                // 1=YES 0=NO
                int nBreakfastFlag = [[arrayBreakfast objectAtIndex:0] intValue];
                UIImage* breakfastImage = [UIImage imageNamed:(nBreakfastFlag == 1 ? @"Yes.png" : @"No.png")];
                UIImageView* breakfastStatusImageView = [[UIImageView alloc] initWithFrame:CGRectMake(60, 10, breakfastImage.size.width, breakfastImage.size.height)];
                breakfastStatusImageView.backgroundColor = [UIColor clearColor];
                breakfastStatusImageView.image = breakfastImage;
                [cell.contentView addSubview:breakfastStatusImageView];
                [breakfastStatusImageView release];
                
                // Lunch
                UILabel* lunchLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 10, 50, 30)];
                lunchLabel.backgroundColor = [UIColor clearColor];
                lunchLabel.font = [UIFont boldSystemFontOfSize:18];
                lunchLabel.textColor = [UIColor blackColor];
                lunchLabel.text = @"午餐:";
                [cell.contentView addSubview:lunchLabel];
                [lunchLabel release];
                
                // Lunch array
                NSArray* arrayLunch = [[detailsDic objectForKey:@"lunch"] componentsSeparatedByString:@"[OVER]"];
                // 1=YES 0=NO
                int nLunchFlag = [[arrayLunch objectAtIndex:0] intValue];
                UIImage* lunchImage = [UIImage imageNamed:(nLunchFlag == 1 ? @"Yes.png" : @"No.png")];
                UIImageView* lunchStatusImageView = [[UIImageView alloc] initWithFrame:CGRectMake(150, 10, lunchImage.size.width, lunchImage.size.height)];
                lunchStatusImageView.backgroundColor = [UIColor clearColor];
                lunchStatusImageView.image = lunchImage;
                [cell.contentView addSubview:lunchStatusImageView];
                [lunchStatusImageView release];
                
                // Supper
                UILabel* supperLabel = [[UILabel alloc] initWithFrame:CGRectMake(200, 10, 50, 30)];
                supperLabel.backgroundColor = [UIColor clearColor];
                supperLabel.font = [UIFont boldSystemFontOfSize:18];
                supperLabel.textColor = [UIColor blackColor];
                supperLabel.text = @"晚餐:";
                [cell.contentView addSubview:supperLabel];
                [supperLabel release];
                
                // Lunch array
                NSArray* arraySupper = [[detailsDic objectForKey:@"supper"] componentsSeparatedByString:@"[OVER]"];
                // 1=YES 0=NO
                int nSupperFlag = [[arraySupper objectAtIndex:0] intValue];
                UIImage* supperImage = [UIImage imageNamed:(nSupperFlag == 1 ? @"Yes.png" : @"No.png")];
                UIImageView* supperStatusImageView = [[UIImageView alloc] initWithFrame:CGRectMake(250, 10, supperImage.size.width, supperImage.size.height)];
                supperStatusImageView.backgroundColor = [UIColor clearColor];
                supperStatusImageView.image = supperImage;
                [cell.contentView addSubview:supperStatusImageView];
                [supperStatusImageView release];
            }
                break;
            case 4: // stay
            {
                //cell.selectionStyle = UITableViewCellSelectionStyleBlue;
                
                // Cell background view
                UIView* cellBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
                UIImageView* bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
                [bgImageView setImage:[UIImage imageNamed:@"CellBackground.png"]];
                [cellBgView addSubview:bgImageView];
                [bgImageView release];
                [cell setBackgroundView:cellBgView];
                [cellBgView release];
                
                // Stay
                UILabel* stayLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 50, 30)];
                stayLabel.backgroundColor = [UIColor clearColor];
                stayLabel.font = [UIFont boldSystemFontOfSize:18];
                stayLabel.textColor = [UIColor blackColor];
                stayLabel.text = @"住宿:";
                [cell.contentView addSubview:stayLabel];
                [stayLabel release];
                
                NSString* stayString = [detailsDic objectForKey:@"stay"];
                if([stayString length])
                {
                    //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                    
                    // Stay array
                    NSArray* arrayStay = [stayString componentsSeparatedByString:@"[OVER]"];
                    UILabel* stayStatusLabel = [[UILabel alloc] initWithFrame:CGRectMake(70, 10, 200, 30)];
                    stayStatusLabel.backgroundColor = [UIColor clearColor];
                    stayStatusLabel.font = [UIFont systemFontOfSize:18];
                    stayStatusLabel.textColor = TEXTCOLOR;
                    stayStatusLabel.text = [arrayStay objectAtIndex:0];
                    [cell.contentView addSubview:stayStatusLabel];
                    [stayStatusLabel release];
                }
                else
                {
                    cell.accessoryType = UITableViewCellAccessoryNone;
                    
                    // Stay array
                    UILabel* stayStatusLabel = [[UILabel alloc] initWithFrame:CGRectMake(70, 10, 200, 30)];
                    stayStatusLabel.backgroundColor = [UIColor clearColor];
                    stayStatusLabel.font = [UIFont systemFontOfSize:18];
                    stayStatusLabel.textColor = TEXTCOLOR;
                    stayStatusLabel.text = @"暂时未定";
                    [cell.contentView addSubview:stayStatusLabel];
                    [stayStatusLabel release];
                }
            }
                break;
            case 5: // tranffic
            {   
                //cell.selectionStyle = UITableViewCellSelectionStyleBlue;
                
                // Cell background view
                UIView* cellBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
                UIImageView* bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
                [bgImageView setImage:[UIImage imageNamed:@"CellBackground.png"]];
                [cellBgView addSubview:bgImageView];
                [bgImageView release];
                [cell setBackgroundView:cellBgView];
                [cellBgView release];
                
                // Traffic
                UILabel* trafficLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 50, 30)];
                trafficLabel.backgroundColor = [UIColor clearColor];
                trafficLabel.font = [UIFont boldSystemFontOfSize:18];
                trafficLabel.textColor = [UIColor blackColor];
                trafficLabel.text = @"交通:";
                [cell.contentView addSubview:trafficLabel];
                [trafficLabel release];
                
                NSString* trafficString = [detailsDic objectForKey:@"traffic"];
                if([trafficString length])
                {
                    //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                    
                    // Traffic array
                    NSArray* arrayTraffic = [trafficString componentsSeparatedByString:@"[OVER]"];
                    UILabel* trafficStatusLabel = [[UILabel alloc] initWithFrame:CGRectMake(60, 10, 240, 30)];
                    trafficStatusLabel.backgroundColor = [UIColor clearColor];
                    trafficStatusLabel.font = [UIFont systemFontOfSize:18];
                    trafficStatusLabel.textColor = TEXTCOLOR;
                    trafficStatusLabel.text = [arrayTraffic objectAtIndex:0];
                    [cell.contentView addSubview:trafficStatusLabel];
                    [trafficStatusLabel release];
                }
                else
                {
                    cell.accessoryType = UITableViewCellAccessoryNone;
                    
                    UILabel* trafficStatusLabel = [[UILabel alloc] initWithFrame:CGRectMake(70, 10, 200, 30)];
                    trafficStatusLabel.backgroundColor = [UIColor clearColor];
                    trafficStatusLabel.font = [UIFont systemFontOfSize:18];
                    trafficStatusLabel.textColor = TEXTCOLOR;
                    trafficStatusLabel.text = @"暂时未定";
                    [cell.contentView addSubview:trafficStatusLabel];
                    [trafficStatusLabel release];
                }
            }
                break;
            default:
                break;
        }
    }
    return cell;
}

#pragma mark -
#pragma mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary* oneDayJourney = [arrayJourneyDetails objectAtIndex:indexPath.section];
    
    ShowImageViewController* showImageViewController = [ShowImageViewController alloc];
    
    showImageViewController.showImageStatus = ShowImageStatus_Others;
    
    switch (indexPath.row)
    {
        case 0: // image
        {
            [showImageViewController release];
            
            return;
        }
        case 1: // Introduction_details
        {
            NSString* introductionDetails = [oneDayJourney objectForKey:@"introduction_details"];
            
            showImageViewController.showImageStatus = ShowImageStatus_JourneyDetails_TextView;
            
            showImageViewController.textViewString = introductionDetails;
            
            /*
            UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
            if(cell.accessoryType == UITableViewCellAccessoryDisclosureIndicator)
            {   
                if(0 != [introduction_details length])
                {
                    NSArray* arrayDetails = [introduction_details componentsSeparatedByString:@"[OVER]"];
                 
                    if([arrayDetails count])
                    {
                        showImageViewController.showImageStatus = ShowImageStatus_JourneyDetails;
                        
                        showImageViewController.arrayInfo = [NSMutableArray arrayWithArray:arrayDetails];
                    }
                    else
                    {
                        [showImageViewController release];
                        
                        return;
                    }
                }
                else
                {
                    [showImageViewController release];
                    
                    return;
                }
            }
            else
            {
                [showImageViewController release];
                
                return;
            }
            */
        }
            break;
        case 2: // sightButtonHandle
        {
            [showImageViewController release];
            
            return;
        }
            break;
        case 3: // 三餐
        {
            [showImageViewController release];
            
            return;
            
            /*
            NSArray* breakfastArray = [[oneDayJourney objectForKey:@"breakfast"] componentsSeparatedByString:@"[OVER]"];
            NSArray* lunchArray = [[oneDayJourney objectForKey:@"lunch"] componentsSeparatedByString:@"[OVER]"];
            NSArray* supperArray = [[oneDayJourney objectForKey:@"supper"] componentsSeparatedByString:@"[OVER]"];

            NSDictionary* breakfastDic = [NSDictionary dictionaryWithObjectsAndKeys:
                                          @"早餐", @"name",
                                          [breakfastArray objectAtIndex:1], @"image",
                                          [breakfastArray objectAtIndex:2], @"description",
                                          nil];
            NSDictionary* lunchDic = [NSDictionary dictionaryWithObjectsAndKeys:
                                          @"午餐", @"name",
                                          [lunchArray objectAtIndex:1], @"image",
                                          [lunchArray objectAtIndex:2], @"description",
                                          nil];
            NSDictionary* supperDic = [NSDictionary dictionaryWithObjectsAndKeys:
                                          @"晚餐", @"name",
                                          [supperArray objectAtIndex:1], @"image",
                                          [supperArray objectAtIndex:2], @"description",
                                          nil];
            NSArray* mealsArray = [NSArray arrayWithObjects:breakfastDic, lunchDic, supperDic, nil];
            
            showImageViewController.title = @"三餐";
            showImageViewController.arrayShowImage = [NSMutableArray arrayWithArray:mealsArray];
            */
        }
            break;
        case 4: // Stay
        {
            [showImageViewController release];
            
            return;
            /*
            UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
            if(cell.accessoryType == UITableViewCellAccessoryDisclosureIndicator)
            {
                NSArray* arrayStay = [[oneDayJourney objectForKey:@"stay"] componentsSeparatedByString:@"[OVER]"];
                
                NSDictionary* stayDic = [NSDictionary dictionaryWithObjectsAndKeys:
                                              [arrayStay objectAtIndex:0], @"name",
                                              [arrayStay objectAtIndex:1], @"image",
                                              [arrayStay objectAtIndex:2], @"description",
                                              nil];
                
                NSArray* stayArray = [NSArray arrayWithObjects:stayDic, nil];
                showImageViewController.title = @"住宿";
                showImageViewController.arrayShowImage = [NSMutableArray arrayWithArray:stayArray];
            }
            else
            {
                [showImageViewController release];
                
                return;
            }
            */
        }
            break;
        case 5: // Traffic
        {
            [showImageViewController release];
            
            return;
            /*
            UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
            
            if(cell.accessoryType == UITableViewCellAccessoryDisclosureIndicator)
            {
                NSArray* arrayTraffic = [[oneDayJourney objectForKey:@"traffic"] componentsSeparatedByString:@"[OVER]"];
                
                NSDictionary* trafficDic = [NSDictionary dictionaryWithObjectsAndKeys:
                                         [arrayTraffic objectAtIndex:0], @"name",
                                         [arrayTraffic objectAtIndex:1], @"image",
                                         [arrayTraffic objectAtIndex:2], @"description",
                                         nil];
                NSArray* trafficArray = [NSArray arrayWithObjects:trafficDic, nil];
                showImageViewController.title = @"交通";
                showImageViewController.arrayShowImage = [NSMutableArray arrayWithArray:trafficArray];
            }
            else
            {
                [showImageViewController release];
                
                return;
            }
            */
        }
            break;
        default:
            break;
    }
    
    [self.navigationController pushViewController:showImageViewController animated:YES];
    [showImageViewController release];
}

#pragma mark -
#pragma mark sightButtonHandle
- (void)sightButtonHandle:(id)sender
{
    UIButton* sightButton = (UIButton*)sender;
    
    UILabel* sightNameLabel;
    if([[sightButton subviews] count] > 1)
    {
        sightNameLabel = (UILabel*)[[sightButton subviews] objectAtIndex:1];
    }
    else
    {
        sightNameLabel = (UILabel*)[[sightButton subviews] objectAtIndex:0];
    }
    
    ShowSightsViewController* showSightsViewController = [ShowSightsViewController alloc];
    
    if([sightNameLabel.text rangeOfString:@"."].location != NSNotFound)
    {
        showSightsViewController.sightName = [[sightNameLabel.text componentsSeparatedByString:@"."] objectAtIndex:1];
    }
    else
    {
        showSightsViewController.sightName = sightNameLabel.text;
    }
    [self.navigationController pushViewController:showSightsViewController animated:YES];
}

#pragma mark -
#pragma mark toolbarButtonItemHandle
- (void)toolbarButtonItemHandle:(id)sender
{
    UIBarButtonItem* barButtonItem = (UIBarButtonItem*)sender;
    switch (barButtonItem.tag)
    {
        case TAG_STOWITEM:
        {   
            if([barButtonItem.title isEqualToString:STOW]) // 收藏
            {
                NSDictionary* parameters = [NSDictionary dictionaryWithObjectsAndKeys:
                                            journeyId, @"journey_id", 
                                            @"1", @"journey_isMyFavorite", nil];
                
                [[NetworkManager sharedNetworkManager] requestServerForMethod:NetworkRequest_UpdateOneJourneyToMyFavorite
                                                               WithParameters:parameters
                                                             AndCallBackScope:self
                                                                AndSuccessSel:@"onSuccessForStow:"
                                                                 AndFailedSel:@"onFailedForStow:"];
                
                [barButtonItem setTitle:UNSTOW];
            }
            else if([barButtonItem.title isEqualToString:UNSTOW]) // 取消收藏
            {
                [barButtonItem setTitle:STOW];
                
                NSDictionary* parameters = [NSDictionary dictionaryWithObjectsAndKeys:
                                            journeyId, @"journey_id", 
                                            @"0", @"journey_isMyFavorite", nil];

                [[NetworkManager sharedNetworkManager] requestServerForMethod:NetworkRequest_UpdateOneJourneyToMyFavorite
                                                               WithParameters:parameters
                                                             AndCallBackScope:self
                                                                AndSuccessSel:@"onSuccessForUnstow:"
                                                                 AndFailedSel:@"onFailedForUnstow:"];
            }
        }
            break;
        case TAG_ACTIONITEM: // Share to sina weibo
        {
            
        }
            break;
        case TAG_COMPOSEITEM: // Send message
        {}
            break;
        default:
            break;
    }
}

#pragma mark -
#pragma mark NetworkManager callback Methods
- (void)onSuccess:(id)sender
{
    NSDictionary* resultDic = (NSDictionary*)sender;
    
    m_nDayCount = [[resultDic objectForKey:@"dayCount"] intValue];
    
    m_nDayNumber = 1;
    
    UITableView* tableView = (UITableView*)[self.view viewWithTag:TAG_TABLEVIEW];
    
    // Get journey list
 //   NSDictionary* dicOneDayJourney = [resultDic objectForKey:@"journey_details"];
    
    [arrayJourneyDetails removeAllObjects];
    [arrayJourneyDetails addObjectsFromArray:[resultDic objectForKey:@"journey_details"]];
    
    [tableView reloadData];
}

- (void)onFailed:(id)sender
{
	NSDictionary* resultDic = (NSDictionary*)sender;
    
    // 暂无数据提示
	UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:SORRY_NODATA 
                                                        message:[resultDic objectForKey:@"message"]
                                                       delegate:self
                                              cancelButtonTitle:@"好的"
                                              otherButtonTitles:nil];
    [alertView show];
    [alertView release];
}

#pragma mark scrollViewDidScroll 上拉刷新
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -
#pragma mark scrollViewDidScroll 上拉刷新
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if(((scrollView.contentOffset.y + scrollView.frame.size.height) > scrollView.contentSize.height - 70) && !bIsLoading)
    {
        if(m_nDayNumber + 1 > m_nDayCount)
        {
            if((int)scrollView.contentOffset.y % 20 == 0)
            {   
//                // TableView footer view
//                UIView* footerView = [[UIView alloc] init];
//                [footerView setFrame:CGRectMake(0, 0, 320, 45)];
//                
//                // 保存行程参考
//                UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//                [button setFrame:CGRectMake(2, 0, 316, 45)];
//                [button setTitle:@"保存行程参考" forState:UIControlStateNormal];
//                [footerView addSubview:button];
//                
//                UITableView* tableView = (UITableView*)[self.view viewWithTag:TAG_TABLEVIEW];
//                tableView.tableFooterView = footerView;
//                [footerView release];
                
                // Bottom view
                BottomView* bottomView;
                bottomView = [[BottomView alloc] initWithFrame:CGRectMake(10, 386, 300, 30)             
                                                          name:@"已经是最后一天了"];
                [self.view addSubview:bottomView];
                [bottomView bottomViewWillAppearWithDuration:2.0];
                [bottomView release];
            }
        }
        else
        {
            bIsLoading = YES;
            
            m_nDayNumber++;
            
            NSDictionary* parameters = [NSDictionary dictionaryWithObjectsAndKeys:
                                        journeyId, @"journeyId", 
                                        [NSString stringWithFormat:@"%d", m_nDayNumber], @"day", nil];
            
            [[NetworkManager sharedNetworkManager] requestServerForMethod:NetworkRequest_GetJourneyDetails
                                                           WithParameters:parameters
                                                         AndCallBackScope:self
                                                            AndSuccessSel:@"onSuccessForNextDay:"
                                                             AndFailedSel:@"onFailedForNextDay:"];
            
            NSString* nameString = [NSString stringWithFormat:@"正在加载第%d天", m_nDayNumber];
            
            BottomView* bottomView = [[BottomView alloc] initWithFrame:CGRectMake(10, 386, 300, 30) 
                                                                  name:nameString];
            [self.view addSubview:bottomView];
            
            [bottomView bottomViewWillAppear];
            
            [bottomView release];
        }
    } 
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{	
}

#pragma mark -
#pragma mark Callback Methods for More 
- (void)onSuccessForNextDay:(id)sender
{
    bIsLoading = NO;
    
    NSDictionary* resultDic = (NSDictionary*)sender;
    
    m_nDayCount = [[resultDic objectForKey:@"dayCount"] intValue];
    
    UITableView* tableView = (UITableView*)[self.view viewWithTag:TAG_TABLEVIEW];
    
    // Get journey list
    [arrayJourneyDetails addObject:[[resultDic objectForKey:@"journey_details"] objectAtIndex:0]];
    
    [tableView reloadData];
}

- (void)onFailedForNextDay:(id)sender
{
    bIsLoading = NO;
    
    m_nDayNumber -= 1;
}

#pragma mark -
#pragma mark Callback Methods for Stow
- (void)onSuccessForStow:(id)sender
{
    NSDictionary* resultDic = (NSDictionary*)sender;
    if([[resultDic objectForKey:@"returnCode"] intValue] == 1)
    {
        StowView* stowView = [[StowView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)
                                                        flag:UNSTOW
                                                    withName:@"收藏成功"];
        [stowView viewWillDisappear];
        [stowView release];
    }
}

- (void)onFailedForStow:(id)sender
{
    
}

#pragma mark -
#pragma mark Callback Methods for Unstow
- (void)onSuccessForUnstow:(id)sender
{
    NSDictionary* resultDic = (NSDictionary*)sender;
    if([[resultDic objectForKey:@"returnCode"] intValue] == 1)
    {
        StowView* stowView = [[StowView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)
                                                        flag:UNSTOW
                                                    withName:@"取消收藏"];
        [stowView viewWillDisappear];
        [stowView release];
    }
}

- (void)onFailedForUnstow:(id)sender
{
    
}

#pragma mark -
#pragma mark shareButtonHandle
- (void)shareButtonHandle:(id)sender
{   
    if (!_engine)
    {
        _engine = [[OAuthEngine alloc] initOAuthWithDelegate: self];
        _engine.consumerKey = kOAuthConsumerKey;
        _engine.consumerSecret = kOAuthConsumerSecret;
    }
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    if([userDefaults objectForKey:@"authData"])
    {   
        // Go to SendMessageViewController
        SendMessageViewController* sendMessageViewController = [SendMessageViewController alloc];
        sendMessageViewController.journeyName = journeyName;
        [self.navigationController pushViewController:sendMessageViewController animated:YES];
        [sendMessageViewController release];
        
        [self performSelector:@selector(loadTimeline) withObject:nil afterDelay:0.5];
    }
    else
    {
        [self performSelector:@selector(loadTimeline) withObject:nil afterDelay:0.5];
    }
}

- (void)loadTimeline {
	UIViewController *controller = [OAuthController controllerToEnterCredentialsWithEngine: _engine delegate: self];
	
	if (controller) 
    {
		[self presentModalViewController: controller animated: YES];
    }
	else 
    {
//		NSLog(@"Authenicated for %@..", _engine.username);
		[OAuthEngine setCurrentOAuthEngine:_engine];
		[self loadData];
	}
}

- (void)loadData {
	if (weiboClient) { 
		return;
	}
	weiboClient = [[WeiboClient alloc] initWithTarget:self 
											   engine:_engine
											   action:@selector(timelineDidReceive:obj:)];
	[weiboClient getFollowedTimelineSinceID:0 
							 startingAtPage:0 count:100];
}

- (void)timelineDidReceive:(WeiboClient*)sender obj:(NSObject*)obj
{
    /*
     NSLog(@"begin timelineDidReceive");
     if (sender.hasError) {
     NSLog(@"timelineDidReceive error!!!, errorMessage:%@, errordetail:%@"
     , sender.errorMessage, sender.errorDetail);
     [sender alert];
     if (sender.statusCode == 401) {
     [self openAuthenticateView];
     }
     }
     weiboClient = nil;
     
     if (obj == nil || ![obj isKindOfClass:[NSArray class]]) {
     return;
     }
     NSArray *ary = (NSArray*)obj;  
     
     [statuses removeAllObjects];
     
     for (int i = [ary count] - 1; i >= 0; --i) {
     NSDictionary *dic = (NSDictionary*)[ary objectAtIndex:i];
     if (![dic isKindOfClass:[NSDictionary class]]) {
     continue;
     }
     Status* sts = [Status statusWithJsonDictionary:[ary objectAtIndex:i]];
     [statuses insertObject:sts atIndex:0];
     }		
     [self.tableView reloadData];
     */
}

//=====================================================================================================
#pragma mark OAuthEngineDelegate
- (void) storeCachedOAuthData: (NSString *) data forUsername: (NSString *) username {
	NSUserDefaults			*defaults = [NSUserDefaults standardUserDefaults];
	
	[defaults setObject: data forKey: @"authData"];
	[defaults synchronize];
    
    // Go to SendMessageViewController
    SendMessageViewController* sendMessageViewController = [SendMessageViewController alloc];
    sendMessageViewController.journeyName = journeyName;
    [self.navigationController pushViewController:sendMessageViewController animated:YES];
    [sendMessageViewController release];
}

- (NSString *) cachedOAuthDataForUsername: (NSString *) username {
	return [[NSUserDefaults standardUserDefaults] objectForKey: @"authData"];
}

- (void)removeCachedOAuthDataForUsername:(NSString *) username{
	NSUserDefaults			*defaults = [NSUserDefaults standardUserDefaults];
	
	[defaults removeObjectForKey: @"authData"];
	[defaults synchronize];
}

//=======================================================================================
#pragma mark OAuthSinaWeiboControllerDelegate
- (void) OAuthController: (OAuthController *) controller authenticatedWithUsername: (NSString *) username {
//	NSLog(@"Authenicated for %@", username);
	[self loadTimeline];
}

- (void) OAuthControllerFailed: (OAuthController *) controller {
//	NSLog(@"Authentication Failed!");
	//UIViewController *controller = [OAuthController controllerToEnterCredentialsWithEngine: _engine delegate: self];
	
	if (controller) 
		[self presentModalViewController: controller animated: YES];
	
}

- (void) OAuthControllerCanceled: (OAuthController *) controller {
//	NSLog(@"Authentication Canceled.");
	//UIViewController *controller = [OAuthController controllerToEnterCredentialsWithEngine: _engine delegate: self];
	
	if (controller) 
		[self presentModalViewController: controller animated: YES];
	
}

#pragma mark -
#pragma mark addLabelOnCell
-(void)addLabelOnCell:(UITableViewCell*)cell
				 text:(NSString*)text
				frame:(CGRect)frame 
			  bgColor:(UIColor*)bgColor 
			textColor:(UIColor*)textColor 
		   fontOfSize:(UIFont*)fontOfSize 
		lineBreakMode:(UILineBreakMode)lineBreakMode 
		textAlignment:(UITextAlignment)textAlignment
{
	if(!bgColor) bgColor = [UIColor grayColor];
	if(!textColor) textColor = [UIColor blackColor];
	if(!fontOfSize) fontOfSize = [UIFont systemFontOfSize:16];
	if(!text) text = [NSString stringWithString:@"请输入Label内容"];
	
	UILabel* titleLabel = [[[UILabel alloc] initWithFrame:frame] autorelease];
	titleLabel.backgroundColor = bgColor;
	titleLabel.textColor = textColor;
	titleLabel.font = fontOfSize;
	titleLabel.lineBreakMode = lineBreakMode;
	titleLabel.textAlignment = textAlignment;
	titleLabel.text = text;
	[cell.contentView addSubview:titleLabel];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
